<template>
  <div class="contract-compoment">
    <div class="header-wrapper">
      <div class="header-title">维保合同管理</div>
      <div v-if="!props.isLook" class="header-btn" @click="addHandle">添加</div>
    </div>
    <div class="data-wrapper">
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          :border="true"
          class="self-stripe-table"
          height="100%"
        >
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="contractName" label="合同名称">
            <template #default="scope">
              <div class="contract-name-wrapper">
                <img
                  src="@/assets/images/合同.png"
                  alt="合同"
                  class="contract-logo"
                />
                <span class="company-name">{{ scope.row.contractName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="supplierName" label="供应商" />
          <el-table-column label="有效期">
            <template #default="scope">
              <div>
                <div>
                  {{ formatDate(scope.row.startDate) }}
                </div>
                <div>至</div>
                <div>
                  {{ formatDate(scope.row.endDate) }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="!props.isLook"
            label="操作"
            width="150"
            align="left"
          >
            <template #default="scope">
              <div class="table-btn" @click="editHandle(scope.row)">编辑</div>
              <div class="table-btn" @click="deleteHandle(scope.row.id)">
                删除
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="addDialogVisible"
      title="添加合同"
      width="50%"
      @close="resetAddForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="合同名称" prop="contractName">
          <el-input
            v-model="addForm.contractName"
            placeholder="请输入合同名称"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input
            v-model="addForm.supplierName"
            placeholder="请输入供应商"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="合同有效期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            format="YYYY/MM/DD"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
            @calendar-change="handleDateRangeChange"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitAddForm"
            :loading="addFormLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, defineProps } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getMaintenanceContractsByDeviceIdAPI,
  addMaintenanceContractAPI,
  deleteMaintenanceContractAPI,
  ContractType,
} from "@/api/service/contract";
import { formatDate } from "@/assets/js/utils";

const route = useRoute();
const deviceId = route.query.id as string;

const props = defineProps<{
  isLook: boolean;
}>();

// 表格数据
const tableData = ref<ContractType[]>([]);
// API调用保护状态
const listApiLoading = ref(false);
function getContractList() {
  // 防止并发调用
  if (listApiLoading.value) return;
  listApiLoading.value = true;

  getMaintenanceContractsByDeviceIdAPI(deviceId)
    .then((_data: any) => {
      const data = _data as ContractType[];
      tableData.value = data;
    })
    .catch(() => {
      ElMessage.error("获取合同列表失败");
    })
    .finally(() => {
      listApiLoading.value = false;
    });
}
getContractList();

// 添加合同
const addDialogVisible = ref(false);
const addFormRef = ref();
const addFormLoading = ref(false);
const addForm = ref({
  id: "",
  contractName: "",
  supplierName: "",
  startDate: "",
  endDate: "",
});
const dateRange = ref<[string, string]>(["", ""]);

// 处理日期范围变化
const handleDateRangeChange = (value: [string, string] | null) => {
  console.log(value);
  if (value && value.length === 2 && value[0] && value[1]) {
    dateRange.value = value;
  }
};

function addHandle() {
  addDialogVisible.value = true;
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}

// 编辑合同
function editHandle(row: ContractType) {
  addDialogVisible.value = true;
  addForm.value = {
    id: row.id,
    contractName: row.contractName,
    supplierName: row.supplierName,
    startDate: row.startDate,
    endDate: row.endDate,
  };
  dateRange.value = [row.startDate, row.endDate];
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}

// 表单验证规则 - 设置为手动触发，避免弹框打开时就显示错误
const addFormRules = {
  contractName: [
    { required: true, message: "请输入合同名称", trigger: "blur" },
  ],
  supplierName: [{ required: true, message: "请输入供应商", trigger: "blur" }],
  dateRange: [
    { required: true, message: "请选择合同有效期", trigger: "change" },
  ],
};

// 重置添加表单
function resetAddForm() {
  addForm.value = {
    id: "",
    contractName: "",
    supplierName: "",
    startDate: "",
    endDate: "",
  };
  dateRange.value = ["", ""];
  addFormRef.value?.clearValidate();
}

// 提交添加表单
function submitAddForm() {
  // 防止并发提交
  if (addFormLoading.value) return;

  addFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      addFormLoading.value = true;
      addMaintenanceContractAPI({
        id: addForm.value.id,
        contractName: addForm.value.contractName,
        supplierName: addForm.value.supplierName,
        deviceId: deviceId,
        startDate: new Date(dateRange.value[0]).getTime(),
        endDate: new Date(dateRange.value[1]).getTime(),
      })
        .then(() => {
          ElMessage.success(addForm.value.id ? "编辑合同成功" : "添加合同成功");
          addDialogVisible.value = false;
          resetAddForm();
          // 刷新列表
          getContractList();
        })
        .catch(({ message }) => {
          ElMessage.error(message);
        })
        .finally(() => {
          addFormLoading.value = false;
        });
    }
  });
}

// 删除合同
function deleteHandle(id: string) {
  ElMessageBox.confirm("确定删除该合同吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteMaintenanceContractAPI(id)
      .then(() => {
        ElMessage.success("删除合同成功");
        getContractList();
      })
      .catch(() => {
        ElMessage.error("删除合同失败");
      });
  });
}
</script>

<style scoped lang="scss">
.contract-compoment {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.header-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1.5rem;
  background-color: $bg-color-page;
  border-bottom: 1px solid $border-color-primary;
  .header-title {
    font-size: $font-size-page-menu;
    font-weight: 600;
    color: $text-color-regular;
    padding-left: 12px;
    border-left: 4px solid $color_brand;
  }
  .header-btn {
    display: inline-flex;
    align-items: center;
    padding: 0.2rem 1rem;
    color: $text-color-regular;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
    background: $bg-td-2-color;
    border-radius: 0.5rem;
  }
  .header-btn:hover {
    text-decoration: underline;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 1.5rem;
  background-color: #fff;
  .table-wrapper {
    padding: 0 0;
    flex: 1;
    min-height: 0;
  }
  .table-btn {
    display: inline-flex;
    align-items: center;
    color: $text-color-regular;
    margin-left: 1rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
  .contract-name-wrapper {
    display: flex;
    align-items: center;
    .contract-logo {
      width: 2rem;
      height: 2rem;
      margin-right: 0.5rem;
    }
    .contract-name {
      font-size: $font-size-base-btn-text;
      color: $text-color-primary;
    }
  }
}
</style>
